<template>
  <div>
    <avue-tree
      v-if="userInfo.isAdmin == 1 || userInfo.isAdmin == 3"
      ref="deptTree"
      :option="treeOption.treeOption"
      :data="treeData"
      class="huilan-tree"
      node-key="id"
      @node-click="nodeClickCurent"
    />
    <avue-tree
      v-else
      ref="deptTree2"
      :option="option"
      :data="data"
      class="huilan-tree"
      node-key="id"
      @node-click="nodeClickCurent"
    >
      <span
        slot-scope="{ node, data }"
        :title="node.label"
        :class="{ selected: node.selected, disabled: node.disabled }"
      >
        {{ node.label }}
      </span>
    </avue-tree>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import {
  getCanBeManagerDeptLazyTree,
  getCanManagerDeptByAccount,
} from "@/api/system/dept";
import { isNull } from "@/util/qsgCommon.js";
export default {
  name: "DynamicTree",
  props: {
    nodeClick: {
      type: Function,
      default() {},
    },
    isDept: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    ...mapGetters(["userInfo", "managerDeptId"]),
    treeOption() {
      const me = this;
      return {
        treeOption: {
          menu: false,
          addBtn: false,
          nodeKey: "id",
          lazy: true,
          props: {
            label: "deptName",
            children: "children",
            // 设置了value后getNode才能通过key获取节点
            value: "id",
          },
          defaultExpandedKeys: ["0"],
          treeLoad: (node, resolve) => {
            let parentId = node.data.id;
            if (node.level === 0) {
              resolve([
                {
                  deptName: this.$t("system.dept.dept"),
                  id: "0",
                  active: false,
                },
              ]);
              return;
            }
            //eslint-disable-next-line
            getCanBeManagerDeptLazyTree(parentId).then((res) => {
              const data = res.data.data.retList || [];
              const root = res.data.data.root || "";
              me.treeItemId = parentId;
              me.treeItem = node;
              //eslint-disable-next-line
              setTimeout(() => {
                if (parentId === "0") {
                  me.root = root;
                  let curNodeId = "0";
                  let curNode = node;
                  let curNodeData = node.data;
                  me.$refs.deptTree.setCurrentKey(curNodeId);
                  me.nodeClickCurent(curNodeData, curNode);
                  if (data.length > 0 && parentId === "0") {
                    me.$refs.deptTree.setCurrentKey(data[0].id);
                    me.nodeClickCurent(data[0], curNode);
                  }
                  if (this.type === "add") {
                    me.$refs.deptTree.setCurrentKey(this.addNode.id);
                    me.nodeClickCurent(this.addNode, curNode);
                  }
                }
              });
              resolve(
                data.map((item) => {
                  return {
                    ...item,
                    leaf: item.isLeaf === "1",
                  };
                })
              );
            });
          },
        },
      };
    },
  },
  data() {
    return {
      treeData: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      node: null,
      resolve: null,
      root: "true",
      treeItemId: null,
      treeItem: null,
      type: "",
      addNode: "",
      //
      option: {
        menu: false,
        addBtn: false,
        nodeKey: "id",
        props: {
          label: "name",
          disabled: "disabled",
          children: "children",
          // 设置了value后getNode才能通过key获取节点
          value: "id",
        },
        defaultExpandedKeys: ["0"],
      },
      data: [],
      managerDept: [],
    };
  },
  mounted() {
    if (this.userInfo.isAdmin == 0) {
      this.managerDept = this.deepClone(this.managerDeptId);
      this.option.defaultExpandedKeys.push(this.managerDept[0]);
      getCanManagerDeptByAccount().then((res) => {
        let data = res.data.data;
        this.data = [
          {
            name: this.$t("system.dept.dept"),
            id: "0",
            children: data,
          },
        ];
        if (!this.isDept) {
          this.traverseTree(this.data);
        }
        setTimeout(() => {
          this.$refs.deptTree2.setCurrentKey("0");
          let curNode = this.$refs.deptTree2.getCurrentNode();
          let item = this.findNodeById(this.data, "0");
          this.nodeClickCurent(item, curNode);
        });
      });
    }
  },
  methods: {
    findNodeById(tree, id) {
      if (!tree || tree.length === 0) return null;

      const findNode = (nodes, id) => {
        for (let i = 0; i < nodes.length; i++) {
          if (nodes[i].id === id) {
            return nodes[i];
          }
          if (nodes[i].children && nodes[i].children.length > 0) {
            const foundNode = findNode(nodes[i].children, id);
            if (foundNode) {
              return foundNode;
            }
          }
        }
        return null;
      };

      return findNode(tree, id);
    },
    traverseTree(node) {
      if (node) {
        node.forEach((item) => {
          let flag = true;
          if (this.managerDept.includes(item.id) || item.id === "0") {
            flag = false;
          }
          if (flag) {
            item.disabled = true;
          } else {
            item.disabled = false;
          }
          this.traverseTree(item.children);
        });
      }
    },
    nodeClickCurent(data, node) {
      // if (data.id === '0') {
      //   if (this.root === "false") {
      //     this.$message.error("没有部门权限");
      //     return;
      //   }
      // } else {
      //   if (data.isManager !== "1") {
      //     this.$message.error("没有部门权限");
      //     return;
      //   }
      // }
      if (isNull(data)) {
        data = {};
      }
      if (!data.disabled) {
        this.nodeClick(data, node, this.root);
      }

      // 修改人员时使用
      // const deptId = this.findObject(this.option.group, "deptId");
      // if (data.ancestors && data.ancestors !== "") {
      //   deptId.defaultExpandedKeys = data.ancestors.split(",");
      // }
    },
    updateTreeNode(type, data) {
      const deptTree =
        this.userInfo.isAdmin == 0 ? this.$refs.deptTree2 : this.$refs.deptTree;
      const curParent = deptTree.getNode(data.parentId);
      if (this.userInfo.isAdmin == 0) {
        data.name = data.deptName;
      }
      this.type = type;
      this.addNode = data;
      if (type === "add" || type === "batchDel") {
        if (type === "add") {
          deptTree.append(data, curParent);
        }
        if (curParent.isLeaf) {
          curParent.isLeaf = false;
          curParent.loaded = false;
          if (!curParent.expanded) {
            curParent.expand();
          }
        } else {
          if (curParent.loaded) {
            curParent.loaded = false;
            curParent.expand();
          } else {
            curParent.expand();
          }
        }
      } else if (type === "update") {
        const curNode = deptTree.getNode(data.id);
        if (curNode) {
          if (this.userInfo.isAdmin == 0) {
            curNode.data.name = data.deptName;
          } else {
            curNode.data = data;
          }
        }
      } else if (type === "del") {
        deptTree.remove(data.id);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.tree-select {
  width: 100%;
}

.tree-scrollbar-wrapper {
  max-height: 50vh;
}

.tree-select-popover {
  .el-tree-node {
    .selected {
      color: #409eff;
      font-weight: 700;
    }
  }
}
.huilan-tree {
  /deep/.el-tree {
    .el-tree-node.is-current {
      .el-tree-node__content {
        border: none;
        background-color: transparent;
      }
    }
    .el-tree-node__content {
      .disabled {
        color: #c7cad3;
      }
    }
  }
}
.popover-reference {
  line-height: normal;
}
</style>
